package com.youshang520i.nacosserviceprovider;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.youshang520i.nacosserviceprovider.model.DataBaseProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author youshang
 */
@SpringBootApplication
public class NacosServiceProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosServiceProviderApplication.class,args);
    }


    @Value("${server.port}")
    public String port;

    @Autowired
    private DataBaseProperties dataBaseProperties;

//    @PostConstruct
    public void init() throws NacosException, InterruptedException {
        System.out.println("port :" + port);

        System.out.println( "dataBaseProperties : " + dataBaseProperties);


//        this.connitNacos();

    }

    public void connitNacos() throws InterruptedException, NacosException {
        String serverAddr = "192.168.3.123";
        String dataId = "application-dev.yaml";
        String group = "DEFAULT_GROUP";
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println("1： "+content);
        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println("recieve:" + configInfo);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });

        boolean isPublishOk = configService.publishConfig(dataId, group, "content");
        System.out.println(isPublishOk);

        Thread.sleep(3000);
        content = configService.getConfig(dataId, group, 5000);
        System.out.println("2： "+content);

        boolean isRemoveOk = configService.removeConfig(dataId, group);
        System.out.println(isRemoveOk);
        Thread.sleep(3000);

        content = configService.getConfig(dataId, group, 5000);
        System.out.println("3： "+content);
        Thread.sleep(3000);
    }

}
